package cn.ffcs.uec.staffAdjustPostApply.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Messagebox;

import cn.ffcs.raptornuke.plugin.common.zk.ctrl.BasePortletComposer;
import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.raptornuke.portal.theme.ThemeDisplay;
import cn.ffcs.uec.common.manager.CustomFilesManager;
import cn.ffcs.uec.common.util.NodeVoUtil;
import cn.ffcs.uec.common.util.UecConstants;
import cn.ffcs.uec.common.vo.UecWaPrmlv;
import cn.ffcs.uec.common.vo.UecWaSeclv;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.manager.ActRunTaskManager;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.salary.manager.UecSalaryProjectManager;
import cn.ffcs.uec.salary.model.UecSalaryProject;
import cn.ffcs.uec.staff.manager.UecPsndocWadocManager;
import cn.ffcs.uec.staff.manager.UecStaffInfoManager;
import cn.ffcs.uec.staff.model.UecPsndocWadoc;
import cn.ffcs.uec.staff.model.UecStaffInfo;
import cn.ffcs.uec.staffAdjustPostApply.action.bean.StaffAdjustPostApprovalViewMainBean;
import cn.ffcs.uec.staffRecords.vo.AtiOaBaseObject;
import cn.ffcs.uom.common.model.DefaultDaoFactory;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;

/**
 * 合同制人员定调资审批弹窗
 * 
 * @author liuxiaodong
 *
 */
@Controller
@Scope("prototype")
public class StaffAdjustPostApprovalViewMainComposer extends
		BasePortletComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2596213606792445601L;

	private StaffAdjustPostApprovalViewMainBean bean = new StaffAdjustPostApprovalViewMainBean();

	private UecStaffInfoManager uecStaffInfoManager = (UecStaffInfoManager) ApplicationContextUtil
			.getBean("uecStaffInfoManager");

	private ActRunTaskManager actRunTaskManager = (ActRunTaskManager) ApplicationContextUtil
			.getBean("actRunTaskManager");

	private UecPsndocWadocManager uecPsndocWadocManager = (UecPsndocWadocManager) ApplicationContextUtil
			.getBean("uecPsndocWadocManager");

	private CustomFilesManager customFilesManager = (CustomFilesManager) ApplicationContextUtil
			.getBean("customFilesManager");

	private UecSalaryProjectManager uecSalaryProjectManager = (UecSalaryProjectManager) ApplicationContextUtil
			.getBean("uecSalaryProjectManager");

	private UecStaffInfo uecStaffInfo;
	/**
	 * 薪资标准等级 == 岗位等级
	 */
	private UecWaPrmlv uecWaPrmlv;
	/**
	 * 薪资标准档别
	 */
	private UecWaSeclv uecWaSeclv;
	/**
	 * 薪资项目
	 */
	private UecSalaryProject uecSalaryProject;

	/**
	 * 薪资变动情况
	 */
	private UecPsndocWadoc uecPsndocWadoc;

	private String taskDefKey;

	private String type;

	private String taskId;

	private AtiOaBaseObject oaBaseObject;

	@Override
	public String getPortletId() {
		return super.getPortletId();
	}

	@Override
	public ThemeDisplay getThemeDisplay() {
		return super.getThemeDisplay();
	}

	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		Components.wireVariables(comp, bean);
	}

	/**
	 * 界面初始化
	 */
	public void onCreate$staffAdjustPostApprovalViewWin() {
		bindCombobox();
		bindBean();
	}

	/**
	 * 绑定combobox
	 */
	private void bindCombobox() {
		// 薪资变动原因
		ListboxUtils.rendererForEdit(bean.getPkChangecause(),
				NodeVoUtil.getDictionaries(UecConstants.WAGE_CHANGE_CAUSE));
	}

	/**
	 * 重新申请
	 * 
	 * @throws InterruptedException
	 */
	public void onOk() throws InterruptedException {

		if (!ApprovalConstants.OP_TYPE_VIEW.equals(type)) {
			// 判断任务是否已被处理
			boolean isCompleted = ApprovalUtil.isTaskCompleted(oaBaseObject,
					taskId);
			if (isCompleted) {
				onCancel();
				Events.postEvent(ApprovalConstants.ON_REFRESH_QUERY_RESPONSE,
						this.self, null);
				ZkUtil.showError("任务不存在或已被处理完毕！", "错误提示");
				return;
			}
			// 校验
			String msg = checkUacStaffData();
			if (null != msg) {
				Messagebox.show(msg);
				return;
			}
			Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK
					| Messagebox.CANCEL, Messagebox.QUESTION,
					new EventListener() {
						@Override
						public void onEvent(Event event) throws Exception {
							if (((Integer) event.getData()).intValue() == Messagebox.OK) {
								postApprovalData();
								onCancel();
							} else {
								return;
							}
						}
					});
		} else {
			this.onCancel();
		}

	}

	/**
	 * 重新提交数据
	 * 
	 * @throws InterruptedException
	 */
	public void postApprovalData() throws InterruptedException {

		String currentName = ApprovalUtil.getCurrentName();
		if (StrUtil.isNullOrEmpty(currentName)) {
			ZkUtil.showError("当前登录用户已失效，请重新登录!", "错误提示");
			return;
		}
		// 薪资起始日期
		uecPsndocWadoc.setBegindate(DateUtil.dateToStr(bean.getBegindate()
				.getValue()));
		// 薪资截止日期
		uecPsndocWadoc.setEnddate(DateUtil.dateToStr(bean.getEnddate()
				.getValue()));
		// 薪资调整日期
		uecPsndocWadoc.setChangedate(DateUtil.dateToStr(bean.getChangedate()
				.getValue()));

		// 变动原因
		uecPsndocWadoc.setPkChangecause(bean.getPkChangecause()
				.getSelectedItem().getValue().toString());
		// 备注
		uecPsndocWadoc.setVnote(bean.getVnote().getValue());
		// 依据文件
		uecPsndocWadoc.setVbasefile(bean.getVbasefile().getValue());

		uecPsndocWadoc.setModifiedtime(DateUtil.getCurrenDate());
		uecPsndocWadoc.setModifier(currentName);
		DefaultDaoFactory.getDefaultDao().updateObject(uecPsndocWadoc);

		Events.postEvent("onOKResponse", this.self,
				ApprovalConstants.ON_OK_RESULT);

	}

	/**
	 * 审批同意
	 * 
	 * @throws InterruptedException
	 */
	public void onApproval() throws InterruptedException {
		Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK | Messagebox.CANCEL,
				Messagebox.QUESTION, new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						if (((Integer) event.getData()).intValue() == Messagebox.OK) {
							approvalData();
						} else {
							return;
						}
					}
				});

	}

	/**
	 * 确认审批同意
	 */
	public void approvalData() {
		Map<String, Object> map = new HashMap<String, Object>();
		String comment = this.getComment(taskDefKey);
		map.put("comment", comment);
		map.put("onApprovalResult", ApprovalConstants.ON_APPROVAL_RESULT);
		Events.postEvent("onApprovalResponse", this.self, map);
		this.onCancel();
	}

	/**
	 * 审批拒绝
	 */
	public void onReject() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("comment", this.getComment(taskDefKey));
		map.put("onRejectResult", ApprovalConstants.ON_REJECT_RESULT);
		Events.postEvent("onRejectResponse", this.self, map);
		this.onCancel();
	}

	/**
	 * 关闭窗口
	 */
	public void onCancel() {
		this.bean.getStaffAdjustPostApprovalViewWin().onClose();
	}

	/**
	 * 页面显示
	 */
	public void bindBean() {
		String procDefName = (String) arg.get("procDefName");
		this.bean.getStaffAdjustPostApprovalViewWin().setTitle(
				procDefName + "审批");

		oaBaseObject = (AtiOaBaseObject) arg.get("oaBaseObject");
		if (!StrUtil.isNullOrEmpty(oaBaseObject)) {
			// 获取审批意见
			PubUtil.fillBeanFromPo(oaBaseObject, bean);
		}
		type = (String) arg.get("opType");
		if (ApprovalConstants.OP_TYPE_VIEW.equals(type)) {
			// 查看历史工单
			setButtonValid(true, false, false);
			setTextValid(true, true, true);
		} else {
			// 审批中弹框
			taskDefKey = (String) arg.get("taskDefKey");
			if ("modify".equals(taskDefKey)) {
				setButtonValid(true, false, false);
				setTextValid(false, false, false);
			} else {
				setButtonValid(false, true, true);
			}
			if ("deptLeaderAudit".equals(taskDefKey)) {
				this.bean.getSecondText().setRows(2);
				this.setTextValid(true, false, false);
				bean.getSecondText().setValue(null);
			}
			if ("hrAudit".equals(taskDefKey)) {
				this.bean.getThirdText().setRows(2);
				this.setTextValid(false, true, false);
				bean.getThirdText().setValue(null);
			}
			if ("hrLeaderAudit".equals(taskDefKey)) {
				this.bean.getFourthText().setRows(2);
				this.setTextValid(false, false, true);
				bean.getFourthText().setValue(null);
			}
		}

		taskId = (String) arg.get("taskId");
		if (!StrUtil.isNullOrEmpty(oaBaseObject)) {
			List<Map<String, Object>> list = actRunTaskManager
					.getRuTasks(oaBaseObject.getProcInstId());
			if (null == list) {
				ZkUtil.showError("未知错误!", "错误信息");
				return;
			}
			if (list.size() == 0) {
				String wadocIdTmp = oaBaseObject.getWadocIdModify();
				oaBaseObject.setWadocIdModify(oaBaseObject.getWadocIdHis());
				oaBaseObject.setWadocIdHis(wadocIdTmp);
			}

			// 获取历史数据
			String staffIdHis = oaBaseObject.getStaffIdHis();
			if (!StrUtil.isNullOrEmpty(staffIdHis)) {
				uecStaffInfo = UecStaffInfo.newInstance();
				uecStaffInfo.setStaffId(Long.parseLong(staffIdHis));
				uecStaffInfo = uecStaffInfoManager
						.quaryUecStaffInfoByStaffId(Long.valueOf(staffIdHis));
				bean.getPsnName().setValue(uecStaffInfo.getName());
				bean.getPsnCode().setValue(uecStaffInfo.getCode());
			}

			String wadocIdHis = oaBaseObject.getWadocIdHis();
			if (!StrUtil.isNullOrEmpty(wadocIdHis)) {
				uecPsndocWadoc = UecPsndocWadoc.newInstance();
				uecPsndocWadoc.setWadocId(Long.valueOf(wadocIdHis));
				uecPsndocWadoc = uecPsndocWadocManager
						.findUecPsndocWadocById(uecPsndocWadoc);
				if (null != uecPsndocWadoc) {
					PubUtil.fillBeanFromPo(uecPsndocWadoc, bean);
					// 是否谈判工资
					if (!StrUtil.isEmpty(uecPsndocWadoc.getNegotiationWage())) {
						if ("Y".equals(uecPsndocWadoc.getNegotiationWage())) {
							bean.getNegotiationWage().setValue("是");
						} else if ("N".equals(uecPsndocWadoc
								.getNegotiationWage())) {
							bean.getNegotiationWage().setValue("否");
						}
					}
					// 是否来自于流程
					if (!StrUtil.isEmpty(uecPsndocWadoc.getWorkflowflag())) {
						if ("Y".equals(uecPsndocWadoc.getWorkflowflag())) {
							bean.getWorkflowflag().setValue("是");
						} else if ("N".equals(uecPsndocWadoc.getWorkflowflag())) {
							bean.getWorkflowflag().setValue("否");
						}
					}
					// 薪资标准类别
					if (!StrUtil.isNullOrEmpty(uecPsndocWadoc.getPkWaGrd())) {
						if ("1001A1100000000B2DPQ".equals(uecPsndocWadoc
								.getPkWaGrd())) {
							bean.getPkWaGrd().setValue("集团薪资标准（新岗新体系）");
						} else if ("1001A1100000000A7FIO".equals(uecPsndocWadoc
								.getPkWaGrd())) {
							bean.getPkWaGrd().setValue("集团薪资标准（旧岗新体系）");
						} else if ("1001A1100000000A83WH".equals(uecPsndocWadoc
								.getPkWaGrd())) {
							bean.getPkWaGrd().setValue("内蒙古薪资标准（旧岗新体系）");
						} else if ("1001A1100000000TRON2".equals(uecPsndocWadoc
								.getPkWaGrd())) {
							bean.getPkWaGrd().setValue("薪资表（旧体系）");
						}
					}
					// 薪资标准
					if (!StrUtil.isNullOrEmpty(uecPsndocWadoc.getPkWaSeclv())
							&& !StrUtil.isNullOrEmpty(uecPsndocWadoc
									.getPkWaPrmlv())) {
						// 薪资级别==岗位等级
						uecWaPrmlv = new UecWaPrmlv();
						uecWaPrmlv.setPkWaPrmlv(uecPsndocWadoc.getPkWaPrmlv());
						uecWaPrmlv = customFilesManager
								.findObjectByUecWaPrmlv(uecWaPrmlv);
						// 薪资档别
						uecWaSeclv = new UecWaSeclv();
						uecWaSeclv.setPkWaSeclv(uecPsndocWadoc.getPkWaSeclv());
						uecWaSeclv = customFilesManager
								.findObjectByUecWaSeclv(uecWaSeclv);
						if (null != uecWaPrmlv && null != uecWaSeclv) {
							if (null != uecWaPrmlv && null != uecWaSeclv) {
								bean.getPkWaPrmlv().setValue(
										uecWaPrmlv.getLevelName());
								bean.getPkWaSeclv().setValue(
										uecWaSeclv.getLevelName());
								bean.getPkWaCrt().setValue(
										uecWaPrmlv.getLevelName() + "/"
												+ uecWaSeclv.getLevelName());
							}
						}
					}
					// 薪资项目
					if (!StrUtil.isNullOrEmpty(uecPsndocWadoc.getPkWaItem())) {
						uecSalaryProject = new UecSalaryProject();
						uecSalaryProject.setPkWaItem(uecPsndocWadoc
								.getPkWaItem());
						uecSalaryProject = uecSalaryProjectManager
								.findObjectByUecSalaryProject(uecSalaryProject);
						if (null != uecSalaryProject) {
							if (!StrUtil.isNullOrEmpty(uecSalaryProject
									.getName())) {
								bean.getPkWaItem().setValue(
										uecSalaryProject.getName());
							}
						}
					}
					// 薪资起始日期
					bean.getBegindateHis().setValue(
							uecPsndocWadoc.getBegindate());
					// 薪资截止日期
					bean.getEnddateHis().setValue(uecPsndocWadoc.getEnddate());
					// 薪资调整日期
					bean.getChangedateHis().setValue(
							uecPsndocWadoc.getChangedate());
					// 变动原因
					bean.getPkChangecauseHis().setValue(
							uecPsndocWadoc.getPkChangecauseName());
					// 备注
					bean.getVnoteHis().setValue(uecPsndocWadoc.getVnote());
					// 依据文件
					bean.getVbasefileHis().setValue(
							uecPsndocWadoc.getVbasefile());
				}
			}

			// 获取审批数据
			String wadocIdModify = oaBaseObject.getWadocIdModify();
			if (!StrUtil.isNullOrEmpty(wadocIdModify)) {
				uecPsndocWadoc = new UecPsndocWadoc();
				uecPsndocWadoc.setWadocId(Long.valueOf(wadocIdModify));
				uecPsndocWadoc = uecPsndocWadocManager
						.findUecPsndocWadocById(uecPsndocWadoc);
				if (null != uecPsndocWadoc) {
					// PubUtil.fillBeanFromPo(uecPsndocWadoc, bean);
					bean.getVbasefile().setValue(uecPsndocWadoc.getVbasefile());
					bean.getVnote().setValue(uecPsndocWadoc.getVnote());
					// 变动原因
					@SuppressWarnings("unchecked")
					List<Listitem> pkChangecauseItem = bean.getPkChangecause()
							.getChildren();
					for (Listitem listitem : pkChangecauseItem) {
						if (null != listitem
								&& !StrUtil.isNullOrEmpty(listitem.getValue())) {
							if (listitem.getValue().toString()
									.equals(uecPsndocWadoc.getPkChangecause())) {
								bean.getPkChangecause().setSelectedItem(
										listitem);
							}
						}
					}
					// 薪资起始日期
					bean.getBegindate().setValue(
							DateUtil.patternStrToDate(uecPsndocWadoc
									.getBegindate()));
					// 薪资截止日期
					bean.getEnddate().setValue(
							DateUtil.patternStrToDate(uecPsndocWadoc
									.getEnddate()));
					// 薪资调整日期
					bean.getChangedate().setValue(
							DateUtil.patternStrToDate(uecPsndocWadoc
									.getChangedate()));
					// 备注
					bean.getVnote().setValue(uecPsndocWadoc.getVnote());
					// 依据文件
					bean.getVbasefile().setValue(uecPsndocWadoc.getVbasefile());
				}
			}
		}
	}

	/**
	 * 获取审批意见
	 * 
	 * @param taskDefKey
	 * @return
	 */
	private String getComment(String taskDefKey) {
		if ("deptLeaderAudit".equals(taskDefKey)) {
			return this.bean.getSecondText().getValue();
		}
		if ("hrAudit".equals(taskDefKey)) {
			return this.bean.getThirdText().getValue();
		}
		if ("hrLeaderAudit".equals(taskDefKey)) {
			return this.bean.getFourthText().getValue();
		}
		return null;
	}

	/**
	 * 设置按钮
	 * 
	 * @param canEdit
	 * @param canApproval
	 * @param canRejects
	 */
	private void setButtonValid(boolean canEdit, boolean canApproval,
			boolean canReject) {
		this.bean.getOkBtn().setVisible(canEdit);
		this.bean.getOkBtn().setDisabled(!canEdit);

		this.bean.getApprovalBtn().setVisible(canApproval);
		this.bean.getApprovalBtn().setDisabled(!canApproval);

		this.bean.getRejectBtn().setVisible(canReject);
		this.bean.getRejectBtn().setDisabled(!canReject);

	}

	/**
	 * 设置审批意见栏
	 * 
	 * @param secondCanEdit
	 * @param thirdCanEdit
	 * @param fourthCanEdit
	 */
	private void setTextValid(boolean secondCanEdit, boolean thirdCanEdit,
			boolean fourthCanEdit) {
		this.bean.getSecondText().setDisabled(!secondCanEdit);
		this.bean.getThirdText().setDisabled(!thirdCanEdit);
		this.bean.getFourthText().setDisabled(!fourthCanEdit);
	}

	/**
	 * 检测填入的参数是否为空
	 */
	private String checkUacStaffData() {
		if (bean.getVnote().getValue().length() > 100) {
			return "备注项所填内容字符数过长";
		} else if (bean.getVbasefile().getValue().length() > 100) {
			return "依据文件项所填内容字符数过长";
		}
		return null;
	}

}
